<?php
	/*
	** File: standard_library
	** Description: This module contains functions that are needed in at least
	** 75% of all page views.
	** Version: 1.0
	** Created: 01/04/2000
	** Author: Andy Jackson
	** Email: Andy.Jackson@solidtech-solutions.co.uk
	*/

	/**
	* Function includeClass

	* Also wrapped by __autoload() in configuration.php
	*/
	function includeClass($strClass)
	{
		if(isset($GLOBALS['arrRegisterClass'][$strClass]) AND 
			file_exists(MODULE . $GLOBALS['arrRegisterClass'][$strClass]))
		{
			include_once(MODULE . $GLOBALS['arrRegisterClass'][$strClass]);
		}else{
			echo "<br/>".MODULE . $GLOBALS['arrRegisterClass'][$strClass];
			//addToLog("Couldn't instantiate $class", LOG_INFORMATION);
		}
	}
	
	function TableHeader($intColCount="1",$strText="&nbsp;",$strPosition="",$strTRDefinition="")	
	{
		echo "<tr>";
			echo "<td valign='top' align='left'><img src='./images/".$strPosition."Left.gif' width='8' height='16' alt=''></td>";
			echo "<td colspan ='".$intColCount."' align='center' $strTRDefinition>".$strText."</td>\n";
			echo "<td valign='top' align='right'><img src='./images/".$strPosition."Right.gif' width='8' height='16' border='0' alt=''></td>";
		echo "</tr>\n";
	}//end function
	
	function switch_background($boBG) 
	{ 
		if($boBG == 0)
		{
			return(BACKG_COLOUR_1);
		}
		Else
		{
		 	return(BACKG_COLOUR_2);
		}
	}//end function 
	
	function print_object($strObject)
	{
		?><pre><?print_r($strObject)?></pre><?
	}
	
	function print_array($array) 
	{ 
		if(gettype($array)=="array") 
			{ 
			echo "<ul>"; 
			while (list($index, $subarray) = each($array) ) 
					{ 
					echo "<li>$index <code>=&gt;</code> "; 
					print_array($subarray); 
					echo "</li>"; 
					} 
			echo "</ul>"; 
			} else echo $array; 
	}//end function  
	
	function print_event($strDataArray,$dtTableCellDate)
	{ 
			while (list($index, $subarray) = each($strDataArray) ) 
			{
				if ($dtTableCellDate == $subarray[dtDate])
				{
				  	echo "<font size=\"-1\"><b>".$subarray[vcEvent];
			     	echo "</b></font><br/>";
				}
	
			}
	}//end function 
	function OpenDb($hostname,$uid,$pwd,$dbname)
	{ 
      $link = mysql_connect($hostname,$uid,$pwd); 
        if($link && mysql_select_db($dbname)){ 
			//echo "$link && mysql_select_db($dbname)";
           return($link); 
         } 
        else
		{ 
			return(FALSE); 
       	} 
	}//end function 
	
	function QueryIntoArray($query){ 
	    settype($retval,"array"); 
		
	    $result= mysql_query($query); 
		
		    if(!$result)
			{ 
			    print "Query Failed"; 
		    }     
		    for($intRecordCount=0;$intRecordCount<mysql_numrows($result);$intRecordCount++)
			{ 
				
		        for($intFieldCount=0;$intFieldCount<mysql_num_fields($result);$intFieldCount++)
				{
					$retval[$intRecordCount][mysql_field_name($result,$intFieldCount)] = mysql_result ($result,$intRecordCount,mysql_field_name($result,$intFieldCount)); 
				}//end inner loop 
		    }//end outer loop 
	
	return $retval; 
	}//end function 
	

	/*
	** Function: ScreenURL
	** Input: $screen, [$secure], [$extra]
	** Output: Function that adds session id and screen to URL.  If $secure is
	**   TRUE, then the URL returned will force SSL mode. Returns something
	**   like:
	**   "http://www.server.com/index.php?SCREEN=welcome"
	**
	**	The extra argument should be an associative array of form variables.
	*/
	function ScreenURL($strScreen, $extra='',$strSecureScreen='',$strParagraph='')
	{
		if($strScreen)
		{//no screen name passed when linking back to homepage
			
			$strSessionSuffix = "";
			
			//If not using cookies append session id
			//if (SID != "")
				//$strSessionSuffix = "&amp;".SID;
				
			if($strParagraph != ''){
				$strParagraph = '#'.$strParagraph;
			}
			
			if(SECURE_SHOP) 
			{
				if(($strScreen == "scrCheckout") || ($strScreen == "scrLogin"))
				{
					/* the following ensures that a site with multiple domains displays the one the cert is for */
					if((defined('SSL_SERVER')) && (SSL_SERVER != ""))
						$URL =    "https://".SSL_SERVER."/".SCRIPT_NAME . "?SCREEN=".$strScreen;
					else 
						$URL =    "https://".SERVER_NAME."/".SCRIPT_NAME . "?SCREEN=".$strScreen;
				}else{
					/* 
					 * Check if using correct URL otherwise redirect to secure URL
					 * this is to get around a problem were basket content lost if moving from one domain to another
					 */
					if((defined('SSL_SERVER')) && (SERVER_NAME != SSL_SERVER))
					{
						$URL =  "http://".SSL_SERVER."/".SCRIPT_NAME . "?SCREEN=".$strScreen;
					}else{
						if(SSL_CONNECTION == TRUE)
						{
							// move away from secure pages
							$URL =    "http://".SERVER_NAME."/".SCRIPT_NAME . "?SCREEN=$strScreen";
						}else 
							$URL = SCRIPT_NAME . "?SCREEN=$strScreen";
					}
				}
				//global $strSecure;
			}else					
				$URL =   SCRIPT_NAME . "?SCREEN=$strScreen";


			//$URL =  SERVER_NAME . EXTERNAL_PATH .  SCRIPT_NAME . "?SCREEN=$screen";

			if(is_array($extra))
			{
				for(reset($extra); $key=key($extra); next($extra))
				{
					if(isset($key))
						$URL .= "&amp;$key=". rawurldecode($extra[$key]);//prepareText($extra[$key]);
				}
			}
			
			if (eregi('bot', BROWSER_NAME)) {
				 // omit session ID
			}else{
				if (   
						(BROWSER_NAME == "ConveraCrawler") || 	  
						(BROWSER_NAME == "ia_archiver") 
					)
				{
					// omit session ID
				}else{
					$URL .= $strSessionSuffix.$strParagraph;//
				}  		 
			}
				
				
		}else{
			//if no screen name passed
		
			if (eregi('bot', BROWSER_NAME)) {
				$URL = "http://".SERVER_NAME."/";
			}else{
					if (   
							(BROWSER_NAME == "ConveraCrawler") || 	  
							(BROWSER_NAME == "ia_archiver") 
						)
					{
						$URL = "http://".SERVER_NAME."/";
					}else{
						$URL = "http://".SERVER_NAME;// "?&amp;".$strParagraph;
					}  		 
			}

    	}
		

		
		return($URL);
	}
	
	/*
	** Function: MenuURL
	** Input: $screen, [$secure], [$extra]
	** Output: Function that adds session id and screen to URL.  If $secure is
	**   TRUE, then the URL returned will force SSL mode. Returns something
	**   like:
	**   "http://www.server.com/index.php?SCREEN=welcome"
	**
	**	The extra argument should be an associative array of form variables.
	*/
	function MenuURL($strScreen, $extra='',$strSecureScreen='')
	{
		if($strScreen){//no screen name passed when linking back to homepage
				/* the following ensures that a site with multiple domains displays the one the cert is for */
				if((SECURE_SHOP) && ($strScreen == "scrCheckout") || (SECURE_SHOP) && ($strScreen == "scrLogin"))
				{
					/* the following ensures that a site with multiple domains displays the one the cert is for */
					if((defined('SSL_SERVER')) && (SSL_SERVER != ""))
						$URL =    "https://".SSL_SERVER."/".SCRIPT_NAME . "?SCREEN=".$strScreen;
					else 
						$URL =    "https://".SERVER_NAME."/".SCRIPT_NAME . "?SCREEN=$strScreen";
					//global $strSecure;
				}else{
					if(SSL_CONNECTION == TRUE){
						// move away from secure pages
						$URL =    "http://".SERVER_NAME."/".SCRIPT_NAME . "?SCREEN=$strScreen";
					}else{
						$URL =    SCRIPT_NAME . "?SCREEN=$strScreen";
					}
				}

				//$URL =  SERVER_NAME . EXTERNAL_PATH .  SCRIPT_NAME . "?SCREEN=$screen";

				if(is_array($extra))
				{
					for(reset($extra); $key=key($extra); next($extra))
					{
						$URL .= "&$key=". $extra[$key];//prepareText($extra[$key]);
					}
				}
				
				
				if (eregi('bot', BROWSER_NAME)) {
					 // omit session ID
				}else{
					if (   
							(BROWSER_NAME == "ConveraCrawler") || 	  
							(BROWSER_NAME == "ia_archiver") 
						)
					{
						// omit session ID
					}else{
						$URL .= "&".SID;
					}  		 
				} 
				
				
		}else{

        	if((BROWSER_NAME == "GoogleBot")||(BROWSER_NAME == "MJ12bot")){
				// omit session ID
				$URL = "http://".SERVER_NAME."/";
			}else{
				$URL .= "http://".SERVER_NAME."/?&amp;".SID;
			}
    	}

		return($URL);
	}

	function ExternalURL($ExternalSite, $screen, $extra='')
	{
		$URL = "http://www.$ExternalSite/".  SCRIPT_NAME . "?SCREEN=$screen&";
		//$URL =  SERVER_NAME . EXTERNAL_PATH .  SCRIPT_NAME . "?SCREEN=$screen";
		
		if(is_array($extra))
		{
			for(reset($extra); $key=key($extra); next($extra))
			{
				$URL .= "&$key=". $extra[$key];//prepareText($extra[$key]);
			}
		}
		$URL .= "&".SID;
		return($URL);
	}
	
	/*
	** Function: ScreenURLCatLink
	*/
	function ScreenURLCatLink($screen, $extra='')
	{
		$URL =    SCRIPT_NAME . "?SESCREEN=$screen";
		//$URL =  SERVER_NAME . EXTERNAL_PATH .  SCRIPT_NAME . "?SCREEN=$screen";
		
		if(is_array($extra))
		{
			for(reset($extra); $key=key($extra); next($extra))
			{
				$URL .= "X1X$key=". $extra[$key];//prepareText($extra[$key]);
			}
		}
		//$URL .= "X1X".SID;
		return($URL);
	}
	
	
	/*
	** Function: StartForm
	** Input: $screen, [$method], [$action], [$secure], [$extra],
	**   [$windowName], [$encodingType], [$formName], [$onReset], [$onSubmit]
	** Output: String
	** Description: Returns necessary form tags to start a form, including SCREEN,
	**   ACTION variables.  If $extra is an array, then key/value pairs will be used to make
	**   extra hidden variables.  The last six arguments are for the case when
	**   you need to override the default tags for some reason.  Empty values will
	**   cause the attributes to be excluded from the FORM tag.
	**
	** Two common encodingTypes are
	**   application/x-www-form-urlencoded	(default)
	**   multipart/form-data	      				(for uploads)
	*/
	function StartForm($screen, $method='get', $action='', $extra='',
		$windowName='', $encodingType='', $formName='', $onReset='', $onSubmit='')
	{
		global $sid;
		
	//if ($screen == "welcome")
		//{
			//$URL =    SCRIPT_NAME;
		//}
		//Else
		//{
			$URL =    SCRIPT_NAME.'?'.SID;	
		//}


		/*
		** opening form tag
		*/
		$FormHead = "<form action=\"$URL\" ";
		$FormHead .= "method=\"$method\" ";

		if($windowName != '')
		{
			$FormHead .= "target=\"$windowName\" ";
		}
		if($encodingType != '')
		{
			$FormHead .= "enctype=\"$encodingType\" ";
		}
		if($formName != '')
		{
			$FormHead .= "name=\"$formName\" ";
		}
		if($onReset != '')
		{
			$FormHead .= "onreset=\"$onReset\" ";
		}
		if($onSubmit != '')
		{
			$FormHead .= "onsubmit=\"$onSubmit\" ";
		}

		$FormHead .= ">\n";


		/*
		** SCREEN
		*/
		$FormHead .= "<input type=\"hidden\" name=\"SCREEN\" value=\"$screen\"/>\n";
		
		
		/*
		** ACTION
		*/
		if($action != '')
		{
			$FormHead .= "<input type=\"hidden\" name=\"ACTION\" value=\"$action\"/>\n";
		}

		/*
		** Extra hidden vars
		*/
		if(is_array($extra))
		{
			for(reset($extra); $key=key($extra); next($extra))
			{
				$FormHead .= "<input type=\"hidden\" name=\"$key\" value=\"";
				$FormHead .= $extra[$key] . "\"/>\n";
			}
		}

		return($FormHead);
	}//end function



	
	/*
	** Function: printActionResults
	** Input:
	** Output:
	** Description: This function is used by layout modules to show
	** any info passed back by action modules.  If you want something 
	** fancier than just a list, tweak this code.
	*
	*/
	
	function printActionResults(){
		global $ActionResults;

		if(is_array($ActionResults)){
			while($message = array_pop($ActionResults)){
				print("<font color=\"#FF0000\">$message</font><br/>\n");
			}
		}
	}//end function
	
	function CreateDropDown($strLabel,$strSQL,$strOnChange="",$strSelected="",$strInitialSelection="Select",$intLimitWidth="500", $boNullSelection = false){ 
	    settype($retval,"array"); 
	    $result= mysql_query($strSQL); 
	    
	    //This was added as a workaround as the default value isn't working when "" is passed through
	    if($intLimitWidth == "")
	    	$intLimitWidth = 500;
	
	    if($result= mysql_query($strSQL)){

	    	if($strOnChange)
	    	{
	    		echo "\n<select id='$strLabel' name='$strLabel' onchange=\"$strOnChange\">\n";
	    	}else{
	    		echo "\n<select id='$strLabel' name='$strLabel'>\n";
	    	}
	    		
	    	if(($strSelected == "")||($boNullSelection))
	    		echo "<option value='' selected='selected'>$strInitialSelection</option>\n";
	    	//}
	    	
		    for($intRecordCount=0;$intRecordCount<mysql_numrows($result);$intRecordCount++)
		    {

		    	$myrow = mysql_fetch_row($result);
		    	echo "<option value='$myrow[0]'";
		    	if ($myrow[0]==$strSelected)
		    	echo " selected='selected'";

		    	if (strlen($myrow[1])>$intLimitWidth)
		    		echo ">".substr(stripslashes($myrow[1]),0,$intLimitWidth)."....";
		    	else
		    		echo ">".$myrow[1];

		    	echo "</option>\n";
		    }
		    
		    echo "</select>\n";
		    return $retval;
	    }else{
	    	//echo "<br/>".$strSQL."<br/>";
	    	print "Query Failed";
	    }
	}//end function 

function SideLink($strScreenName,$strArray='',$strLinkTitle){
	echo "\n<tr valign='top'>";
		echo "<td>&nbsp;>";
		echo "</td>";
		echo "<td>";
		//echo "screen ".$strScreenName."<br/>";
		echo "<a href='".ScreenURL($strScreenName,$strArray)."'>";
		//print("<a href=\"" . ScreenURL(scrProducts,array('nCategoryID'=>2)) . "\">");
		echo "$strLinkTitle";
		echo "</a>";
		echo "</td>";
	echo "</tr>\n";
}//end SideLink

//Write 
function TRTD($strColSpan='',$strText='&nbsp;'){
	echo "\n<tr>";
		echo "<td $strColSpan>$strText";
		echo "</td>";
	echo "</tr>\n";
}//end TRTD

function CreateDropDownRange($strLabel="cbo",$intStartRange="0",$intEndRange="10",$strOnChange="",$strSelected="",$strInitialSelection="00",$strHalfOptions=""){ 
    settype($retval,"array"); 

		
		echo "<select name='$strLabel' onChange=\"$strOnChange\">\n";  
		if ($strSelected=="")
		{
			echo "\n<option value=\"\" selected>$strInitialSelection";
		}
	    for($intRecordCount=$intStartRange;$intRecordCount<=$intEndRange;$intRecordCount++)
		{
	
			echo "\n</option><option value=$intRecordCount";
			if ($intRecordCount==$strSelected)
			{
				echo " selected\n";
			}
			
			if($intRecordCount<10){
				print (">0$intRecordCount");
			}else{
				print (">$intRecordCount");
			}		
	    } 
		echo "</option></select>\n";
return $retval; 
}//end function 

function CountRecords($strTable){ 

	if (!$result = mysql_query("select count(*) from $strTable")){
		array_push($ActionResults, mysql_error());
		return(false);
	}else{
		$myrowcount = mysql_fetch_array($result);
		return($myrowcount[0]);
	}		
		

}//end function 

function DateAdd($datDate,$intDateAmount,$strPeriod="day",$strDatePart="d/m/Y"){
	//$strDatePart = "m"; //"d/m/Y"
	//$datDate = "25/01/2001";
	//$strPeriod = "day";
	//$intDateAmount = 40;
	$tmpDate = explode("/", $datDate); 
	
	
	switch ($strPeriod) {
	
	    case "day":
			return date($strDatePart, mktime(0,0,0,$tmpDate[1], $tmpDate[0]+$intDateAmount,$tmpDate[2]));
	        break;
		case "month":
			return date($strDatePart, mktime(0,0,0,$tmpDate[1]+$intDateAmount, $tmpDate[0],$tmpDate[2]));
	        break;
		case "year":
			return date($strDatePart, mktime(0,0,0,$tmpDate[1], $tmpDate[0],$tmpDate[2]+$intDateAmount));
	        break;
	}
}// end function

function AddImageRollover($strImageID,$strImageName,$intWidth='120',$intHeight='30'){
	echo " onMouseOut=\"ImageSwap('".$strImageID."','./images/".$strImageName."Normal.gif')\""; 
	echo " onMouseOver=\"ImageSwap('".$strImageID."','./images/".$strImageName."Over.gif')\""; 
	echo " onMouseDown=\"ImageSwap('".$strImageID."','./images/".$strImageName."Down.gif')\">";
	echo "<img src='images/".$strImageName."Normal.gif' name='".$strImageID."' width='$intWidth' height='$intHeight' border='0'  alt='".$strImageName.".gif' />";
}//end AddImageRollover

function EchoMySqlRow($InputArray){
echo "<table border=1>";
	while (list($name, $value) = each($InputArray)) {
		echo "<tr>";
			echo "<td>$name = </td>";
	   		echo "<td>$value </td>\n";
		echo "</tr>";
	}
echo "</table>";
}//end EchoMySqlRow

function RandomPassword($intPasswordLength=8) {
   srand ((double)microtime()*1000000);
   $strPassword = '';
   for ($intLoop=0; $intLoop<$intPasswordLength; $intLoop++) { // make $pword $length chars long
      $strLetter = rand(0,61); // 10 digits + 26 Uppercase + 26 lowercase
      if ($strLetter<=9) {
         $strPassword .= $strLetter;  // digits
      } elseif ($strLetter <= 35) {
         $strPassword .= chr($strLetter+55); // Uppercase
      } else {
         $strPassword .= chr($strLetter+61); // Lowercase
      }
   }
   return $strPassword;
}


Function CreateThumbNail($strImagePath="./images/product/",$strImageName,$intNewImageWidth=100,$strthumbz="",$intNewImageHeight=""){
	ini_set("memory_limit","64M");
	$strSourceImage = $strImagePath.$strImageName; // Your image
	//$intNewImageWidth = 100; // Width of new Image
	
	//##### Computer Takes Over ########
	
	 $arrSourceImageSize = GetImageSize($strSourceImage); 
	 $intSourceImageWidth = $arrSourceImageSize[0]; 

	 $intSourceImageHeight = $arrSourceImageSize[1]; 
	 $intSourceImageType = $arrSourceImageSize[2]; 
	 
		 if($intNewImageHeight != ""){
		 	 //$intNewImageHeight = $intNewImageHeight;
			 $intNewImageWidthtRatio = $intSourceImageHeight / $intNewImageHeight; 
			 $intNewImageWidth = $intSourceImageWidth / $intNewImageWidthtRatio;
		 
		 }else{
			 //$intNewImageWidth = $intNewImageWidth;
			 $intNewImageHeightRatio = $intSourceImageWidth / $intNewImageWidth; 
			 $intNewImageHeight = $intSourceImageHeight / $intNewImageHeightRatio;
		 }
	 
		if($intSourceImageWidth < $intNewImageWidth){
			//array_push($ActionResults, "Image not resized to ".$intNewImageWidth." as it is already ".$intSourceImageWidth." pixels wide");
		}else{

		// Shrink Image
			 if ($intSourceImageType == 1) { 
			     //header ("Content-type: image/gif"); 
				 /*
			     $src = imagecreatefromgif("$strSourceImage"); 
			     $im = imagecreate($intNewImageWidth,$intNewImageHeight); 
			     imagecopyresized($im,$src,0,0,0,0,$intNewImageWidth,$intNewImageHeight,$intSourceImageWidth,$intSourceImageHeight); 
			     imagegif($im); 
			     imagedestroy($im); 
			  	*/
			 } else if ($intSourceImageType == 2) { 
			    // header ("Content-type: image/jpeg"); 
			     $src = imagecreatefromjpeg($strSourceImage); 
			     //$src = open_image("$strSourceImage"); 
			     //$im = imagecreate($intNewImageWidth,$intNewImageHeight);
				 $im = ImageCreateTrueColor($intNewImageWidth,$intNewImageHeight);	
				 //  imageinterlace($im,1);
			     imagecopyresampled($im,$src,0,0,0,0,$intNewImageWidth,$intNewImageHeight,$intSourceImageWidth,$intSourceImageHeight); 
				 imagejpeg($im, $strImagePath.$strthumbz.$strImageName,100);
			     imagedestroy($im); 
			  
			 } else if ($intSourceImageType == 3) { 
			     //header ("Content-type: image/png"); 
				 /*
			     $src = imagecreatefrompng("$strSourceImage"); 
			     $im = imagecreate($intNewImageWidth,$intNewImageHeight); 
			     imagecopyresized($im,$src,0,0,0,0,$intNewImageWidth,$intNewImageHeight,$intSourceImageWidth,$intSourceImageHeight); 
			     imagepng($im); 
			     imagedestroy($im); 
			  	*/
			 } else { 
			     echo "This format is not supported!"; 
			 }
		}
}

function DisplayLookupValue($strTable,$strField,$intFieldID){ 
	$strDisplayLookupValueSQL = "SELECT $strField FROM $strTable WHERE ID = $intFieldID";
	//echo $strDisplayLookupValueSQL;
    $strResult = mysql_query($strDisplayLookupValueSQL); 

	    if(!$strResult){ 
	        print "Query Failed"; 
	    } else { 
		//echo "ok".mysql_numrows($strResult);
			for($intRecordCount=0;$intRecordCount<mysql_numrows($strResult);$intRecordCount++){
					$arrRow = mysql_fetch_array($strResult);
					$retval = $arrRow[0];
					//echo "next";
		
			}
	    } 

return $retval; 
}//end function 

// Format MySQL date into English date
function ReformatFromMySqlDate($strDate){
	$tmpDate = explode("-", $strDate); 
	$retval = $tmpDate[2]."-".$tmpDate[1]."-".$tmpDate[0];
	return $retval; 
}//end function

function ReformatToMySqlDate($strDate){
	$tmpDate = explode("-", $strDate); 
	$retval = $tmpDate[2]."-".$tmpDate[1]."-".$tmpDate[0];
	return $retval; 
}//end function

function SendMime($subject, $msgbody, $tomail, $fmail, $fname,$strHeader,$strFooter="&nbsp;",$strEmailCC="") {
    $boundary="-892222071-940147120-978605369=:2749";
    $message = strip_tags($msgbody);
	$message .= "\nYour e-mail reader does not support MIME. \n";
    $message .= "Please ignore the remainder of the message.\n\n";
    $message .= "--$boundary\nContent-Type: text/plain\n\n";
    $message .= "\n\n";
    $message .= "--$boundary\nContent-Type: text/html; charset=\"iso-8859-1\"\n\n";
	$message .= "<table border ='0' class='Normal' cellpadding='0'  cellspacing='0' align='center' width='600'>";
	$message .= "<tr>";
	$message .= "<td>";
    $message .= $strHeader;
	$message .= "</td>";
	$message .= "</tr>";
	$message .= "<tr>";
	$message .= "<td>";
	$message .= $msgbody;
	$message .= "</td>";
	$message .= "</tr>";
	$message .= "<tr>";
	$message .= "<td>";
	$message .= $strFooter;
	$message .= "</td>";
	$message .= "</tr>";
	$message .= "</table>";
    $message .= "\n--$boundary--\n";
    mail($tomail, $subject, $message, "From: \"$fname\" <$fmail>\nMIME-Version: 1.0\nX-Mailer: PHP/" . phpversion() .
	 "\nContent-Type: multipart/alternative;\n  boundary=\"$boundary\"");
	 
	 //As Bcc doesn't work send seperately.
		if ($strEmailCC) {
			mail($strEmailCC, "Copy of Email to $tomail $subject", $message, "From: \"$fname\" <$fmail>\nX-Mailer: PHP/" . phpversion() .
			 "\nContent-Type: multipart/alternative;\n  boundary=\"$boundary\"");
		}
}//End Function

function DeleteFile($strFileToBeDeleted){

	if(!(file_exists($strFileToBeDeleted))){
		return($strFileToBeDeleted." doesn't exist.");
	}else{
		if(unlink($strFileToBeDeleted)){
			return($strFileToBeDeleted." deleted.");
		}else{
			return("deletion of ".$strFileToBeDeleted." failed.");
		}
	}

}//End Function DeleteFile

function CountProducts(){
	
	$strSQL = "select count(*)
				 from tblProduct";

	if (!$result = mysql_query($strSQL)){
		array_push($ActionResults, mysql_error());
		echo "failed";
		return("Products are being updated..");
	}else{
		$myrowcount = mysql_fetch_array($result);
		return($myrowcount[0]);
	}
}//End Function CountProducts

function DisplayBasketButons(){
	if($SCREEN == "scrDisplayOrder"){
		//echo $SCREEN."scrDisplayOrder";
	}else{
		//<img src='./images".//SITE_SUFFIX."/shoppingcart.gif' border='0' alt=''>
		echo "<div align='right'>				 
				<a href=\"" . ScreenURL("scrCart") . "\">
				<img src='./images".SITE_SUFFIX."/editbasket.gif' border='0' alt='Edit shopping basket' />
				</a>
				<br/><br/>
				</div>
				<div align='right'>
				<a href=\"" . ScreenURL("scrCheckout") . "\">
				<img src='./images".SITE_SUFFIX."/buychosenitems.gif' border='0' alt='' />
				</a>
			</div>
		";
	}
}//End Function DisplayBasketButons



function DisplayIndividualProductLink($intChosenProductID){

	return (ScreenURL(("scrListProductItem"),array('nProdID'=>$intChosenProductID)));
	//ScreenURL(("ListProductsAndSubCategory"),array('intSubCategoryID'=>132,'strDirection'=>"First"))
}//end DisplayIndividualProductLink	 

function DisplayListProductItemLink($intChosenProductID){

	return (ScreenURL(("ListProductItem"),array('nProdID'=>$intChosenProductID)));
	//ScreenURL(("ListProductsAndSubCategory"),array('intSubCategoryID'=>132,'strDirection'=>"First"))
}//end DisplayIndividualProductLink

function DisplaySubCatLink($intChosenSubCatID,$intChosenCategoryID=""){

	return (ScreenURL(("ListProductsAndSubCategory"),array('nCategoryID'=>$intChosenCategoryID,'intSubCategoryID'=>$intChosenSubCatID,'strDirection'=>"First")));
	//
}//end DisplaySubCatLink

function DisplayCategoryLink($intChosenCategoryID){

	return (ScreenURL(("scrListProducts"),array('nCategoryID'=>$intChosenCategoryID,'strDirection'=>"First")));
	//
}//end DisplayCategoryLink

function BasketButtonscrListProducts($intCategoryID,$intItem,$intWidth,$intHeight,$strAltText="add to basket"){

	return ("<a href=\"" . ScreenURL("scrListProducts",array('strDirection'=>"Current",'nCategoryID'=>$intCategoryID,'ACTION'=>"actAddItem",'intItem'=>$intItem,'nProdID'=>$intItem) ) . "\"><img src='./buttonset".SITE_SUFFIX."/addtobasket.gif' width='$intWidth' height='$intHeight' alt='$strAltText' border='0' /></a>");

}//end BasketButtonscrListProducts

function BasketButtonListProductsAndSubCategory($intSubCategoryID,$intItem,$intWidth,$intHeight,$strAltText="add to basket",$nCategoryID=""){
	return ("<a href=\"" . ScreenURL("ListProductsAndSubCategory",array('strDirection'=>"Current",'intSubCategoryID'=>$intSubCategoryID,'ACTION'=>"actAddItem",'intItem'=>$intItem,'nProdID'=>$intProdID,'nCategoryID'=>$nCategoryID) ) . "\"><img src='./buttonset".SITE_SUFFIX."/addtobasket.gif' border='0' height='$intHeight' alt='$strAltText' /></a>");
}//end BasketButtonscrListProductsAndSubCategory

function BasketButton($strScreen,$intItem,$intWidth,$intHeight,$strAltText="add to basket"){
	return ("<a href=\"" . ScreenURL($strScreen,array('ACTION'=>"actAddItem",'intItem'=>$intItem) ) . "\"><img src='./buttonset".SITE_SUFFIX."/addtobasket.gif' height='$intHeight' alt='$strAltText' border='0' /></a>");
}//end BasketButtonscrListProductsAndSubCategory


function BasketButtonListProductItem($intSubCategoryID,$intItem,$intWidth,$intHeight,$strAltText="add to basket",$strProductRange="",$nCategoryID=""){
	return ("<a href='".ScreenURL("ListProductItem",array('strDirection'=>"Current",'intSubCategoryID'=>$intSubCategoryID,'ACTION'=>"actAddItem",'intItem'=>$intItem,'nProdID'=>$intItem,'strProductRange'=>$strProductRange,'nCategoryID'=>$nCategoryID) )."'><img src='./buttonset".SITE_SUFFIX."/addtobasket.gif' height='$intHeight' alt='$strAltText' border='0' /></a>");
}//end BasketButtonListProductItem	

function BasketButtonListscrCart($intSubCategoryID,$intItem,$intWidth,$intHeight,$strAltText="add to basket",$strProductRange,$strBackTo){
	return ("<a href=\"" . ScreenURL("scrCart",array('strDirection'=>"Current",'intSubCategoryID'=>$intSubCategoryID,'ACTION'=>"actAddItem",'intItem'=>$intItem,'nProdID'=>$intItem,'strProductRange'=>$strProductRange,'strBackTo'=>$strBackTo) ) . "\"><img src='./buttonset".SITE_SUFFIX."/addtobasket.gif' border='0' height='$intHeight' alt='$strAltText' border='0' /></a>");
}//end BasketButtonListscrCart

function BasketButtonscrListProductItem($nCategoryID,$intItem,$intWidth,$intHeight,$strAltText="add to basket"){
	return ("<a href=\"" . ScreenURL("scrListProductItem",array('strDirection'=>"Current",'nCategoryID'=>$nCategoryID,'ACTION'=>"actAddItem",'intItem'=>$intItem,'nProdID'=>$intItem) ) . "\"><img src='./buttonset".SITE_SUFFIX."/addtobasket.gif' border='0' height='$intHeight' alt='$strAltText'/></a>");
}//end BasketButtonListProductItem



/**
	 * MySqlResults class
	 */
class MySqlResults	{

	var $msgbody;
	var $result;
	var $myrow;
	var $numrows;
	var $numfields;
	var $SQL;
	var $ErrorMessages;
	
	  /**
	   * Enter description here...
	   *
	   * @param string $strSQL
	   * @return MySqlResults
	   */
      function MySqlResults($strSQL){
        //global $_SESSION['sesDebug'];
	  	// $this->strResults = $this->$this->strSQL;
   		$this->SQL = $strSQL;
		echo isset($_SESSION['sesDebug'])?"MySqlResults1: ".$this->SQL."<br/>":"";

			if (!$this->result = mysql_query($this->SQL))
			{
				global $SCRIPT_FILENAME;
				global $Browser_Name;
				global $_UserName;
				//$Browser_Name
				$this->ErrorMessages = mysql_error();
				$subject = "SQL error ".$_SERVER["HTTP_HOST"];
				$msgbody = "<p>
								<b>Script</b>".$SCRIPT_FILENAME."<br/>
								<b>Browser</b> : $Browser_Name<br/>
								<b>SQL error</b> : ".mysql_error()."<br/>
								<b>SQL</b> : ".$this->SQL."<br/>
								<b>User</b> : $_UserName<br/>									
								<b>Screen</b> : ".$_REQUEST['SCREEN']."<br>";
				if(isset($_REQUEST['ACTION']))
					$msgbody .= "<b>Action</b> : ".$_REQUEST['ACTION']."<br>";
					$msgbody .= "<b>Time</b> : ".date('l jS \of F Y h:i:s A')."
							</p>";
				$tomail = "andy@solidtech-solutions.co.uk";
				$fmail = "error@".WEB_DOMAIN;
				$fname = "";
				$strHeader= "";
				include (MODULE . "/navigation/EmailHeader");
				SendMime($subject, $msgbody, $tomail, $fmail, $fname,$strHeader);
				//sendEmail ($tomail, $subject, $msgbody, $fname);
				$this->ErrorMessages .= "An alert has been sent to the technical support team.";
				return(FALSE);
			}else{
				// If SELECT query return results in array $myrow
				echo isset($_SESSION['sesDebug'])?"MySqlResults2: ".$this->SQL."<br/>":"";
				$this->numrows = mysql_num_rows($this->result);
				$this->numfields = mysql_num_fields($this->result);
				if (substr(ltrim($this->SQL),0,6) == "SELECT")
					$this->myrow = mysql_fetch_array($this->result);
				else
					$this->ErrorMessages;
				
				return(TRUE);
			}
			

     }// end class function
}//End class MySqlResults	





/*
    +----------------------------------------------------------------------+
    | Copyright (c) 2000 J.A.Greant                                        |
    | (See end of file for usage notes and licensing information.)         |
    +----------------------------------------------------------------------+
*/

class credit_card
{
    function clean_no ($cc_no)
    {
        // Remove non-numeric characters from $cc_no
        return ereg_replace ('[^0-9]+', '', $cc_no);
    }

    function identify ($cc_no)
    {
         $cc_no = credit_card::clean_no ($cc_no);

        // Get card type based on prefix and length of card number
        if (ereg ('^4(.{12}|.{15})$', $cc_no))
            return 'Visa';
        if (ereg ('^5[1-5].{14}$', $cc_no))
            return 'Mastercard';
        if (ereg ('^3[47].{13}$', $cc_no))
            return 'American Express';
        if (ereg ('^3(0[0-5].{11}|[68].{12})$', $cc_no))
            return 'Diners Club/Carte Blanche';
        if (ereg ('^6011.{12}$', $cc_no))
            return 'Discover Card';
        if (ereg ('^(3.{15}|(2131|1800).{11})$', $cc_no))
            return 'JCB';
        if (ereg ('^2(014|149).{11})$', $cc_no))
            return 'enRoute';

        return 'unknown';
    }

    function validate ($cc_no)
    {
        // Reverse and clean the number
        $cc_no = strrev (credit_card::clean_no ($cc_no));
        
        // VALIDATION ALGORITHM
        // Loop through the number one digit at a time
        // Double the value of every second digit (starting from the right)
        // Concatenate the new values with the unaffected digits
        for ($ndx = 0; $ndx < strlen ($cc_no); ++$ndx)
            $digits .= ($ndx % 2) ? $cc_no[$ndx] * 2 : $cc_no[$ndx];
        
        // Add all of the single digits together
        for ($ndx = 0; $ndx < strlen ($digits); ++$ndx)
            $sum += $digits[$ndx];

        // Valid card numbers will be transformed into a multiple of 10
        return ($sum % 10) ? FALSE : TRUE;
    }

    function check ($cc_no)
    {
        $valid = credit_card::validate ($cc_no);
        $type  = credit_card::identify ($cc_no);
        return array ($valid, $type, 'valid' => $valid, 'type' => $type);
    }
}
/*
    +----------------------------------------------------------------------+
    | FILE NAME: credit_card.pkg                                           |
    +----------------------------------------------------------------------+
    | Author: J.A.Greant                                                   |
    | Email : zak@nucleus.com                                              |
    | Date  : 2000/11/23                                                   |
    +----------------------------------------------------------------------+
    | The credit_card class provides methods for cleaning, validating and  |
    | identifying the type of credit card number. The validation algorithm |
    | and identification procedures are based on information found at:     |
    |          http://www.beachnet.com/~hstiles/cardtype.html              |
    |                                                                      |
    | credit_card::clean_no() method                                       |
    | ------------------------------                                       |
    | Strips all non-numeric characters from the passed value and returns  |
    | an integer.  This method is called by the other methods in the       |
    | credit_card class.                                                   |
    |                                                                      |
    | USAGE EXAMPLE:                                                       |
    | $cc_no ="5454 5454 5454 5454"; // Has spaces for readability         |
    | $cleaned_cc_no = credit_card::clean_no ($cc_no);                     |
    | print $cleaned_cc_no; // Displays 5454545454545454                   |
    |                                                                      |
    | credit_card::identify() method                                       |
    | ------------------------------                                       |
    | Finds the type of credit card (Mastercard, Visa, etc...) based on    |
    | the length and format of the credit card number.  The method can     |
    | identify American Express, Diners Club/Carte Blanche, Discover,      |
    | enRoute, JCB, Mastercard and Visa cards.                             |
    |                                                                      |
    | USAGE EXAMPLE:                                                       |
    | $cc_no ="5454 5454 5454 5454";                                       |
    | print credit_card::identify ($cc_no); // Returns "Mastercard"        |
    |                                                                      |
    | credit_card::validate() method                                       |
    | ------------------------------                                       |
    | Validate a credit card number using the LUHN formula (mod 10).       |
    | Note that many other kinds of card and account numbers are based on  |
    | the LUHN algorith - including Canadian Social Insurance Numbers.     |
    |                                                                      |
    | USAGE EXAMPLE:                                                       |
    | $cc_no ="5454 5454 5454 5454";                                       |
    | print credit_card::validate ($cc_no); // Returns TRUE                |
    |                                                                      |
    | credit_card::check() method                                          |
    | ---------------------------                                          |
    | The check() method validates and identifies a credit card, returning |
    | an array. Indexes 0 and 'valid' will contain TRUE if the card number |
    | is valid (FALSE if it isn't), while indexes 1 and 'type' will        |
    | the type of card (if known). The presence of the numeric keys allows |
    | the method to be used with the list() function.                      |
    |                                                                      |
    | USAGE EXAMPLE:                                                       |
    | $cc_no ="4111 1111 1111 1111";                                       |
    | list ($valid, $type) = credit_card::check ($cc_no);                  |
    | print $valid; // Displays 1 (TRUE)                                   |
    | print $type;  // Displays "Visa"                                     |
    +----------------------------------------------------------------------+

    +----------------------------------------------------------------------+
    | CVS LOG INFO                                                         |
    +----------------------------------------------------------------------+
      $Log: standard_library.php,v $
      Revision 1.6  2008/08/03 09:55:28  andy
      *** empty log message ***

      Revision 1.5  2008/07/22 22:26:10  andy
      Changes to display otherinfo field at top on order related screens.

      Revision 1.4  2008/07/01 05:49:52  andy
      *** empty log message ***

      Revision 1.3  2008/06/28 01:50:09  andy
      *** empty log message ***

      Revision 1.8  2008/06/15 08:32:33  andy
      Latest version of WYSWIG html editor.
      Fixed cart pack quantity problems.

      Revision 1.7  2008/05/14 08:26:33  andy
      Changed Thumbnail creation to resample rather than resize.

      Revision 1.6  2008/04/29 07:43:48  andy
      *** empty log message ***

      Revision 1.5  2008/04/11 22:25:54  andy
      *** empty log message ***

      Revision 1.3  2008/03/27 21:24:11  andy
      *** empty log message ***

      Revision 1.1  2008/02/24 04:58:02  andy
      Initial load of vendere e-commerce software

      Revision 1.2  2000/11/24 07:02:15  zak
      Added top copyright notice

      Revision 1.1  2000/11/24 06:58:42  zak
      Initial commit of credit card class to repository.
      Cleaned and modified code.
      Also rewrote significant parts of code so that I could change to the
      more friendly BSD-style license.


    +----------------------------------------------------------------------+
    | Copyright (c) 2000 J.A.Greant (jag@nucleus.com)                      |
    | All rights reserved.                                                 |
    +----------------------------------------------------------------------+
    | Redistribution and use in source and binary forms, with or without   |
    | modification, is permitted provided that the following conditions    |
    | are met:                                                             |
    +----------------------------------------------------------------------+
    | Redistributions of source code must retain the above copyright       |
    | notice, this list of conditions and the following disclaimer.        |
    |                                                                      |
    | Redistributions in binary form must reproduce the above copyright    |
    | notice, this list of conditions and the following disclaimer in the  |
    | documentation and/or other materials provided with the distribution. |
    |                                                                      |
    | Neither the name of the author nor the names of any contributors to  |
    | this software may be used to endorse or promote products derived     |
    | from this software without specific prior written permission.        |
    |                                                                      |
    | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
    | ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT  |
    | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
    | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE       |
    | AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,           |
    | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
    | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;     |
    | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER     |
    | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT   |
    | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN    |
    | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE      |
    | POSSIBILITY OF SUCH DAMAGE.                                          |
    +----------------------------------------------------------------------+
*/

function RegisterScreen(){
	if( (isset($_SESSION['sesUserType'])) && ($_SESSION['sesUserType'] == 'customer'))
	{
		echo "<a href='". ScreenURL("DisplayOwnDetails")."'>";
		$GLOBALS["strRegisterText"] = "My Details";
	}else{
		echo "<a href='". ScreenURL("EnterCustomer")."'>";
		$GLOBALS["strRegisterText"] = "Register";
	}
}//end RegisterScreen

function LoginScreen(){
	if(isset($_SESSION['sesUserName'])){
		echo "<a href='". ScreenURL("scrLogout")."'>";
		$GLOBALS["strLoginText"] = "Log Out";
	}else{
		echo "<a href='". ScreenURL("scrLogin")."'>";
		$GLOBALS["strLoginText"] = "Log In";
	}
}//end LoginScreen



// include MIME mailer class


	class Mailer{
	
		var $sender;
	
		var $recipient;
	
		var $subject;
	
		var $headers=array();
	
		function Mailer($sender,$recipient,$subject,$message){
	
			// validate incoming parameters
	
			if(!preg_match("/^.+@.+$/",$sender)){
	
				trigger_error('Invalid value for email sender.',E_USER_ERROR);
	
			}
	
			if(!preg_match("/^.+@.+$/",$recipient)){
	
				trigger_error('Invalid value for email recipient.',E_USER_ERROR);
	
			}
	
			if(!$subject||strlen($subject)>255){
	
				trigger_error('Invalid length for email subject.',E_USER_ERROR);
	
			}
	
			if(!$message){
	
				trigger_error('Invalid value for email message.',E_USER_ERROR);
	
			}
	
			$this->sender=$sender;
	
			$this->recipient=$recipient;
	
			$this->subject=$subject;
	
			$this->message=$message;
	
			// define some default MIME headers
	
			$this->headers['MIME-Version']='1.0';
	
			$this->headers['Content-Type']='multipart/mixed;boundary="MIME_BOUNDRY"';
	
			$this->headers['From']='<'.$this->sender.'>';
	
			$this->headers['Return-Path']='<'.$this->sender.'>';
	
			$this->headers['Reply-To']=$this->sender;
	
			$this->headers['X-Mailer']='PHP 4/5';
	
			$this->headers['X-Sender']=$this->sender;
	
			$this->headers['X-Priority']='3';
	
		}
	
		// create text part of the message
	
		function buildTextPart(){
	
			return "--MIME_BOUNDRYnContent-Type: text/plain; charset=iso-8859-1nContent-Transfer-Encoding: quoted-printablennn".$this->message."nn";
	
		}
	
		// create message MIME headers
	
		function buildHeaders(){
	
			foreach($this->headers as $name=>$value){
	
				$headers[]=$name.': '.$value;
	
			}
	
			return implode("n",$headers)."nThis is a multi-part message in MIME format.n";
	
		}
	
		// add new MIME header
	
		function addHeader($name,$value){
	
			$this->headers[$name]=$value;
	
		}
	
		// send email
	
		function send(){
	
			$to=$this->recipient;
	
			$subject=$this->subject;
	
			$headers=$this->buildHeaders();
	
			$message=$this->buildTextPart()."--MIME_BOUNDRY--n";
	
			if(!mail($to,$subject,$message,$headers)){
	
				trigger_error('Error sending email.',E_USER_ERROR);
	
			}
	
			return true;
	
		}
	
	}
    /**
     * Remove slashes and change " to &quot 
     * This is generally used when a form is reprocessing data
     * @param $strInput
     */
    function cleanFormInput($strInput)
    {
    	return (stripslashes(eregi_replace('\"', "&quot;", trim($strInput))));
    }
?>